package middlewares

import (
	"github.com/gin-gonic/gin"
	"strings"
	"zong-go/pkg/auth"
	"zong-go/pkg/cache"
	"zong-go/pkg/response"
)

func JwtMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		authorization := strings.Fields(context.Request.Header.Get("Authorization"))
		if len(authorization) < 2 {
			context.Abort()
			response.ResponseUnauthorized(context, "Unauthorized.")
		} else {
			token := authorization[1]
			// 校验token
			if u, err := auth.ParseToken(token); err != nil {
				context.Abort()
				response.ResponseUnauthorized(context, "Token expires.")
			} else {
				// 查找 redis 是否存在用户信息
				if !cache.Exists("UserCache_" + u.Id) {
					context.Abort()
					response.ResponseUnauthorized(context, "Token expires.")
				}
			}
		}
		//处理请求
		context.Next()
	}
}
